package com.masterclient.app.base;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.EditText;

import com.eoner.baselib.activity.FCActivitySupportProtocol;
import com.eoner.baselib.activity.FCBaseActivity;
import com.eoner.baselib.presenter.FCBasePresenter;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.permission.JumpPermissionManagement;
import com.eoner.baselibrary.utils.CookieNewUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.version.VersionManager;
import com.masterclient.app.modules.main.manager.ScanManager;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
/**
 * 文件名：GZGManagerActivity (待下沉到manager)
 * 描 述：业务层BaseActivity
 * 作 者：gyq
 * 时 间：2021-1-22
 */
public abstract class FCBusinessActivity<T extends FCBasePresenter> extends FCBaseActivity<T> {

    //扫码进入的code
    private String mQrCode;
    public String intentSource;

    @Override
    protected void initTasks() {
        super.initTasks();
        mQrCode = getIntent().getStringExtra("qrcode");
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      生命周期
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
//        Log.i("Uxcam", "onStop: "+System.currentTimeMillis());
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;
            //全局变量isActive = false 记录当前已经进入后台
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onResume(this);
        if ("SplashActivity".equals(getClass().getSimpleName())){
            return;
        }
        if (!isActive || "MainActivity".equals(getClass().getSimpleName()) && ((FCActivitySupportProtocol)this).currentSelPosition() == 0) {
            //app 从后台唤醒,进入前台
            VersionManager.getInstance()
                    .setActivity(getActivity())
                    .checkVersionUpdate(false);
            isActive = true;
        }
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            if (mQrCode != null&&!ScanManager.getScanManager().isShowDialog()) {
                ScanManager.getScanManager().showWelfareDialog(FCBusinessActivity.this);
            }
        }
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      cookie
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 同步cookie
     *
     * @param url 地址
     * @param cookieList 需要添加的Cookie值,以键值对的方式:key=value
     */
    private void syncCookie (String url, ArrayList<String> cookieList) {
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (cookieList != null && cookieList.size() > 0) {
            for (String cookie : cookieList) {
                cookieManager.setCookie(url, cookie);
            }
        }
        cookieManager.setCookie(url, "Domain=.xrkmall.com");
        String cookies = cookieManager.getCookie(url);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.getInstance().sync();
        }
    }

    public void setAppInfoCookies () {
        ArrayList<String> cookieList = new ArrayList<>();
        cookieList.add("platform=android");
        cookieList.add("device=" + CookieNewUtil.getDevicedId());
        cookieList.add("native_token=" + SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN));
        cookieList.add("version=" + CookieNewUtil.getVersionName(this));
        cookieList.add("deviceToken=" + Config.DEVICE_TOKEN);
        cookieList.add("device_id=" + Config.DEVICE_ID+Config.GZG_TEST_USER);
        syncCookie(".xrkmall.com", cookieList);
    }


    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      键盘
    //
    /////////////////////////////////////////////////////////////////////////////////

    public void hideSoftInput(EditText et) {
        InputMethodManager inputManager = (InputMethodManager)et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if ( inputManager.isActive( ) ) {
            inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
        }
    }

    public void showSoftInput(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();

        InputMethodManager inputManager = (InputMethodManager)et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(et, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == JumpPermissionManagement.ALERT_WINDOW_REQUEST_CODE){
            //悬浮窗权结果回调
            RxBus rxBus = RxBus.$();
            rxBus.post(Config.ALERT_PERMISSION_EVENT,"");
        }
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                     工具
    //
    /////////////////////////////////////////////////////////////////////////////////

    protected void startActivitryWithBundle(@NonNull Class clazz, String[][] val) {
        Intent intent = new Intent(this, clazz);
        Bundle bundle = new Bundle();
        if (val != null) {
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void initEtHint(EditText editText, String hintText, int size){
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(hintText);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size,true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }


}
